package top.qingyunge.autumn.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.NonNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import top.qingyunge.autumn.annotation.IgnoreResponseAdvice;
import top.qingyunge.autumn.vo.Result;

import java.util.Objects;

@RestControllerAdvice(basePackages = "top.qingyunge.autumn.controller")
public class GlobalResponseAdvice implements ResponseBodyAdvice<Object> {

    @Resource
    private ObjectMapper objectMapper;
    @Override
    public boolean supports(
            MethodParameter returnType,
            @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        // 检查注解，如果方法或类上有 @IgnoreResponseAdvice 注解，则不处理
        if (returnType.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class) ||
                Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }

        // 如果返回值类型本身就是 Result，则不处理
        return !returnType.getParameterType().equals(Result.class);

    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            @NonNull MethodParameter returnType,
            @NonNull MediaType selectedContentType,
            @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
            @NonNull ServerHttpRequest request,
            @NonNull ServerHttpResponse response
    ) {
        // 如果返回的是 null（例如void方法），包装一个成功的响应
        if (body == null) {
            return Result.success(null);
        }
        //如果Controller返回String的话，SpringBoot不会帮我们自动封装而直接返回，因此我们需要手动转换成json。
        if (body instanceof String) {
            try {
                return objectMapper.writeValueAsString(Result.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        //如果返回的结果是Result对象，即已经封装好的，直接返回即可。双保险
        if (body instanceof Result) {
            return body;
        }

        return Result.success(body);
    }
}